import type { UseFetchOptions } from 'nuxt/app'

export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

export function useRequest<T = any>(
  url: string,
  options?: any
) {
  const config = useRuntimeConfig()
  const authStore = useAuthStore()

  const defaultOptions: any = {
    baseURL: config.public.apiBase,
    
    // 请求拦截
    onRequest({ options }: any) {
      // 添加认证令牌
      const token = authStore.token
      if (token) {
        options.headers = options.headers || {}
        options.headers.Authorization = `Bearer ${token}`
      }
    },

    // 响应拦截
    onResponse({ response }: any) {
      const data = response._data
      
      // 统一处理错误
      if (data?.code !== 200) {
        throw createError({
          statusCode: data?.code || 500,
          message: data?.message || '请求失败',
        })
      }
    },

    // 错误处理
    onResponseError({ response }: any) {
      const data = response._data
      
      // 401 未授权，跳转登录
      if (response.status === 401) {
        authStore.logout()
        navigateTo('/auth/login')
      }
      
      // 显示错误提示
      console.error(data?.message || '请求失败')
    },
  }

  return useFetch<T>(url, {
    ...defaultOptions,
    ...options,
  })
}

// 便捷方法
export const useGet = <T = any>(url: string, options?: any) => {
  return useRequest<T>(url, { ...options, method: 'GET' })
}

export const usePost = <T = any>(url: string, body?: any, options?: any) => {
  return useRequest<T>(url, { ...options, method: 'POST', body })
}

export const usePut = <T = any>(url: string, body?: any, options?: any) => {
  return useRequest<T>(url, { ...options, method: 'PUT', body })
}

export const useDelete = <T = any>(url: string, options?: any) => {
  return useRequest<T>(url, { ...options, method: 'DELETE' })
}